`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    22:09:25 03/25/2014 
// Design Name: 
// Module Name:    enemy 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module enemy_AI_circle (clk,
                        rand,
                        new_enemy,
                        position_x, 
                        position_y,
                        position_valid);
input clk,new_enemy;//if an new enemy needs to be generated, the module will detect the posedge of the generation_require signal.
input [15:0] rand;
output reg [9:0] position_x, position_y;
output reg position_valid;//if the enemy is out of range, the signal will goes to 0.


reg [20:0] freq_count_x, freq_count_y;
reg x_clk;
reg y_clk;
reg x_clk_previous,new_enemy_previous;
reg y_clk_previous;
reg [23:0] circle_y [319:0];
reg [23:0] circle_x [319:0];
reg [9:0] circle_counter;
reg [9:0] position_y_start;

initial freq_count_x <= 0;
initial freq_count_y <= 0;
initial position_valid <= 1;
initial position_x <= 10'd660; 
initial position_y <= 10'd240; 
initial x_clk <= 0;
initial y_clk <= 0; 
initial x_clk_previous=0; 
initial new_enemy_previous=0;
initial y_clk_previous=0; 
initial $readmemh("circle_positions_y.txt", circle_y);
initial $readmemh("circle_positions_x.txt", circle_x);

always @ (posedge clk)
begin
	x_clk_previous <= x_clk;
	if (freq_count_x == 1680000)//speed on the x_axis
	begin
		x_clk <= ~x_clk;
		freq_count_x <= 0;
	end
	else
		freq_count_x <= freq_count_x + 1;
	
	y_clk_previous <= y_clk;
	if (freq_count_y == 1680000)//speed on the y_axis
	begin
		y_clk <= ~y_clk;
		freq_count_y <= 0;
	end
	else
		freq_count_y <= freq_count_y + 1;
	
	new_enemy_previous <= new_enemy;
	if (new_enemy_previous == 0 & new_enemy == 1)
		position_x <= 10'd560;
	else
		if (x_clk_previous == 0 & x_clk == 1)
			position_x <= position_x - 1 -circle_x[circle_counter]+circle_x[circle_counter-1]
                                         -circle_x[circle_counter]+circle_x[circle_counter-1];
                                       //  -circle_x[circle_counter]+circle_x[circle_counter-1];

	
	if (new_enemy_previous == 0 & new_enemy == 1)
        begin
            position_y_start <= 100+rand[8:2];//initial y coordinates
            position_y <= 100+rand[8:2];
        end
    else
		if (y_clk_previous == 0 & y_clk == 1)
            begin
            if (circle_counter == 319)
               circle_counter <= 0;
            else
                circle_counter <= circle_counter + 1;
                position_y <= position_y_start + circle_y[circle_counter];
			end	

	if (position_x < 5 | position_y < 100 | position_y > 320)
		position_valid <= 0;
	else
		position_valid <= 1;
		
end
endmodule
